package client.netty;

import client.TankClient;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.ReferenceCountUtil;
import server.code.ResponseStatus;
import server.netty.GpcDataPackage;

/**
 * 客户端数据报处理器
 * @author lijiahao
 */
public class ClientDataHandler extends SimpleChannelInboundHandler<GpcDataPackage> {

	private final TankClient client;
	
	public ClientDataHandler(TankClient client) {
		this.client = client;
	}
	
	@Override
	protected void channelRead0(ChannelHandlerContext context, GpcDataPackage response) throws Exception {
		try {
			if(response.getStatus() == 1 && response.getCode() == ResponseStatus.accepted) {
				System.out.println("接受到server响应数据: " + response.toString());
				client.setClientId(response.getUnique());
				client.start();
			} else {
				System.out.println("接受到server响应数据: " + response.toString());
			}
			responseMessage(response);
		} finally {
			ReferenceCountUtil.release(response);
		}
	}
	
	@Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
    }
 
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }

    private void responseMessage(GpcDataPackage response) {
		this.client.messageResponse(response);
	}

}
